package com.geekaca.d09.work;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public class Test1 {
    public static void main(String[] args) throws IOException {
        // 搜索文件,然后把文件,文件名,完整路径写到一个单独的txt中
        File file = new File("StudyIO1/src");
        FileOutputStream fos = new FileOutputStream("./searchResult.txt");
        ArrayList<File> fileList = new ArrayList<>();
        fileList = searchFile(file, fileList);
//        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < fileList.size(); i++) {
            File curFile = fileList.get(i);
            String fileInfo = "文件名: " + curFile.getName() + " 路径: " + curFile.getAbsolutePath() + "\r\n";
//            sb.append(fileInfo);
            try {
                fos.write(fileInfo.getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }finally {

                }
            }

        fos.close();
        }




//        System.out.println(fileList);




    public static ArrayList<File> searchFile(File dir, ArrayList<File> fileList) {
        if (dir != null && dir.isDirectory()) {
            File[] files = dir.listFiles();

            if (files.length != 0) {
                for (int i = 0; i < files.length; i++) {
                    File curFile = files[i];
                    if (curFile.isFile()) {
                        fileList.add(curFile);
                    } else {
//                        System.out.println(curFile.getAbsolutePath() + " 是文件夹");
                        searchFile(curFile, fileList);
                    }
                }
            }
        }
        return fileList;
    }
}
